package com.letoken.platform.pub.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.List;


/**
 * 幂等处理，用于防重复提交或防重复执行一个方法
 */
@Component
public class RedisIdeTool {
    public final static String  BLOCK_TX_STR = "BLOCK_TX_STR:%s";

    public final static String  WITHDRAW_SEQ = "WITHDRAW_SEQ:%s";

    public final static String MALL_PAY_CONSUMER = "MALL_PAY_CONSUMER:%s";

    public final static String TASK_RUNNING = "TASK_RUNNING:%s";

    private final static String expire = "172800";// 48小时


    private final static String kvScript =
            "local v = redis.call('EXISTS', KEYS[1]) " +
                    "if v == 1 " +
                    "then " +
                    "return 0 " +
                    "end " +
                    "redis.call('SET',KEYS[1],'1') " +
                    "redis.call('EXPIRE',KEYS[1],ARGV[1]) " +
                    "return 1";


    private final static DefaultRedisScript<Long> checkAndSetStr;
    static {
        checkAndSetStr = new DefaultRedisScript<>(kvScript,Long.class);
    }


    private StringRedisTemplate redisTemplate;

    @Autowired
    private RedisIdeTool(StringRedisTemplate redisTemplate){
        this.redisTemplate = redisTemplate;
    }

    public Boolean checkAndSetStr(String key,String x){
        List<String> keys = Arrays.asList(new String[]{String.format(key,x)});
        long r = redisTemplate.opsForValue().getOperations().execute(checkAndSetStr,keys,expire);
        return  r > 0l ? true : false;
    }


    public void delStr(String key,String x){
        if (StringUtils.hasLength(x))
           redisTemplate.delete(String.format(key,x));
    }



}
